<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserRealname;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;

class UserRealnameController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID搜索'
        ]);
        $builder->addScreen('mobile', 'input', 'mobile', [
            'placeholder' => '手机号搜索'
        ]);
        $builder->addScreen('name', 'input', '姓名', [
            'placeholder' => '姓名搜索'
        ]);
        $builder->addScreen('examine', 'select', '状态', [
            'options' => Examine::getOptions()
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/UserRealname/examine',
            'path' => '/UserRealname/examine',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::WAIT['value']
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('cannel', '取消实名', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/UserRealname/cannel',
            'method' => 'delete',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::YES['value']
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认取消该改用户实名认证',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumn('name', '姓名', [
                'width' => 120,
            ])
            ->addColumn('idcard_number', '身份证号', [
                'width' => 160,
            ])
            ->addColumn('gender', '性别', [
                'width' => 100,
            ])
            ->addColumn('nation', '民族', [
                'width' => 100,
            ])
            ->addColumn('birthday', '出生日期', [
                'width' => 120,
            ])
            ->addColumn('address', '地址', [
                'minWidth' => 120,
            ])
            ->addColumn('issue', '签发机关', [
                'width' => 120,
            ])
            ->addColumn('expire_start', '签发日期', [
                'width' => 120,
            ])
            ->addColumn('expire_end', '失效日期', [
                'width' => 120,
            ])
            ->addColumnEle('front', '人像面', [
                'params' => [
                    'type' => 'image',
                    'props' => [
                        'preview' => true
                    ]
                ],
            ])
            ->addColumnEle('back', '国徽面', [
                'params' => [
                    'type' => 'image',
                    'props' => [
                        'preview' => true
                    ]
                ],
            ])
            ->addColumnEle('examine', '审核', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '审核结果', [
                'minWidth' => 120,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['a.saas_appid', '=', $request->saas_appid]
        ];
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['a.uid', '=', $uid];
        }
        $mobile = $request->get('mobile');
        if ($mobile) {
            $where[] = ['u.mobile', '=', $mobile];
        }
        $name = $request->get('name');
        if ($name) {
            $where[] = ['a.name', 'like', "%{$name}%"];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['a.examine', '=', $examine];
        }
        $data = MassageUserRealname::where($where)
            ->alias('a')
            ->join('MassageUser u', 'u.id = a.uid')
            ->order('a.create_time desc')
            ->field('a.*,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->expire_long) {
                    $item->expire_end = '长期';
                }
            });
        return $this->successRes($data);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageUserRealname = MassageUserRealname::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageUserRealname) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageUserRealname->examine = $D['examine'];
            Db::startTrans();
            try {
                $MassageUser = MassageUser::where('id', $MassageUserRealname->uid)->find();
                $MassageUser->realname = $MassageUserRealname->name;
                $MassageUser->idcard = $MassageUserRealname->idcard_number;
                $MassageUserRealname->message = '';
                if ($MassageUserRealname->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写审核结果');
                    }
                    $MassageUserRealname->message = $D['message'];

                    $MassageUser->realname = '';
                    $MassageUser->idcard = '';
                }
                $MassageUserRealname->save();
                if (!$MassageUser->birthday && $MassageUserRealname->birthday) {
                    $MassageUser->birthday = $MassageUserRealname->birthday;
                }
                if (!$MassageUser->gender && $MassageUserRealname->gender) {
                    if ($MassageUserRealname->gender == '男') {
                        $MassageUser->gender = 'man';
                    } else {
                        $MassageUser->gender = 'woman';
                    }
                }
                $MassageUser->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            $notice = new Notice();
            $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageUserRealname->uid])
                ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                ->field('u.nickname,u.mobile,uw.openid')
                ->find();
            if ($MassageUser) {
                $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
            }
            $notice->saas_appid = $MassageUserRealname->saas_appid;
            $notice->type = NoticeType::EXAMINE['value'];
            $notice->role = ['USER'];
            if ($MassageUserRealname->examine == Examine::NO['value']) {
                $notice->setData([
                    'type' => '实名认证',
                    'state' => '已驳回',
                    'result' => $MassageUserRealname->message,
                    'trade' => $MassageUserRealname->id,
                    'time' => date('Y-m-d H:i:s')
                ]);
            } else {
                $notice->setData([
                    'type' => '实名认证',
                    'state' => '已通过',
                    'result' => '恭喜您，您的实名认证已通过',
                    'trade' => $MassageUserRealname->id,
                    'time' => date('Y-m-d H:i:s')
                ]);
            }
            $notice->send();
            return $this->success('审核成功');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 12,
            'options' => Examine::getOptions()
        ]);
        $builder->addRow('message', 'textarea', '审核结果', '', [
            'col' => 12,
        ]);
        $builder->addDivider('身份信息');
        $builder->addComponent('name', 'info', '姓名', '', [
            'col'           => 6
        ]);
        $builder->addComponent('idcard_number', 'info', '身份证号', '', [
            'col'           => 6
        ]);
        $builder->addComponent('front', 'el-image', '人像面', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageUserRealname->front,
                'width'     => 160,
                'height'    => 220
            ]
        ]);
        $builder->addComponent('back', 'el-image', '国徽面', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageUserRealname->back,
                'width'     => 160,
                'height'    => 220
            ]
        ]);
        $data = $builder->setData($MassageUserRealname)->create();
        return $this->successRes($data);
    }
    public function cannel(Request $request)
    {
        $id= $request->post('id');
        $MassageUserRealname = MassageUserRealname::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserRealname) {
            return $this->fail('数据不存在');
        }
        Db::startTrans();
        try {
            $MassageUserRealname->examine = Examine::NO['value'];
            $MassageUserRealname->message = '取消实名认证';
            $MassageUserRealname->save();
            $MassageUser = MassageUser::where('id', $MassageUserRealname->uid)->find();
            $MassageUser->realname = '';
            $MassageUser->idcard = '';
            $MassageUser->save();
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $notice = new Notice();
        $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageUserRealname->uid])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.nickname,u.mobile,uw.openid')
            ->find();
        if ($MassageUser) {
            $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
        }
        $notice->saas_appid = $MassageUserRealname->saas_appid;
        $notice->type = NoticeType::EXAMINE['value'];
        $notice->role = ['USER'];
        $notice->setData([
            'type' => '实名认证',
            'state' => '已驳回',
            'result' => $MassageUserRealname->message,
            'trade' => $MassageUserRealname->id,
            'time' => date('Y-m-d H:i:s')
        ]);
        $notice->send();
        return $this->success('取消成功');
    }
}
